import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ApiService } from '@core/services/http/api.service';
import { UserAuthService } from '@core/services/user-auth.service';
import {ApesMessageService} from "@shared/apes/message";

@Component({
  selector: 'store-index',
  templateUrl: './store-index.component.html',
  styleUrls: ['./store-index.component.scss']
})
export class StoreIndexComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [
    {hide: true, style: 'default', label: '刷新', id: 'action_query'}
  ];
  title = '';
  ctx = {model: {}};

  /** Grid 相关 **/
  resultData:any;
  gridOptions:GridOptions;
  pinnedBottomRowData:any[] = [];
  columnDefs:any[] = [];
  getContextMenuItems:any;
  height = 275 + 'px';
  posts :any ;                // 获取登录角色所在门店ID
  times: string;

  vipList: any[];              // 获取保养年卡
  vipListRI = {};
  vipListYUE = {};

  bxData: any[];               // 获取保险转化
  bxListRI = {};
  bxListYUE = {};

  nkData: any[];               // 获取年卡统计
  nkListRI = {};
  nkListYUE = {};

  headData: any[];
  headList = {};
  headYUEList = {};

  constructor(private apiService:ApiService,
              private gridConfigService:GridConfigService,
              private userAuthService: UserAuthService,
              private msg: ApesMessageService) {

    const userInfo = this.userAuthService.getUserInfoObj();
    if(userInfo.userAccount.post.branchObj !== undefined) {
      this.posts = userInfo.userAccount.post.branchObj.origin;
      // if(userInfo.userAccount.post.dept !== undefined) {
      //   this.posts = userInfo.userAccount.post.dept.id;
    }else {
      this.posts = null;
    }

    this.queryData();

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 6,
      rowHeight: 35
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();

  }

  ngOnInit() {
      this.getNk();
      this.vipList = this.getVipBY();
      this.bxData = this.getBxData();
      this.nkData = this.getNkData();
      this.headData = this.getHeadData();
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data:any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.queryData();
      }
    }
  }

  queryData() {
    this.times = new Date().toISOString().slice(0, 10);
    this.getVip();
    this.getBx();
    this.getNk();
    this.getHead();
    for(let i=0,len= this.reportList.length; i< len; i ++){
      this.reportList[i].rowData = [];
      let api = this.reportList[i].api;
      this.getTablesData(api, i);
    }
  }

  getHeadData() {
    return [{
      headData: [
        { headerName: '总车流', field: 'JRZCL' },
        { headerName: '在店车流', field: 'ZDCL' },
        { headerName: '服务业绩', field: 'FWXSJE' },
        { headerName: '洗车台次', field: 'XCTC' },
        { headerName: '保养台次', field: 'XBYTC' },
        { headerName: '洗车转化36项台次', field: 'XCZHTC' },
        { headerName: '洗车转36项检测率', field: 'XCJCL' },
      ]
    }]
  }

  getBxData() {
    return [{
      bxData : [
        { headerName: '保险转化', field: 'BXZH'},
        { headerName: '报价数', field: 'BJS'},
        { headerName: '下单数', field: 'XDS'},
        { headerName: '下单金额', field: 'XDJE'},
        { headerName: '转化率', field: 'ZHL'}
      ]
    }]
  }

  getVipBY() {
    return [{
      vipData : [
        { headerName: '保养年卡转化', field: 'TJRQ'},
        { headerName: '到店总车辆', field: 'CLDDSL'},
        { headerName: '新增车辆', field: 'XZCSL'},
        { headerName: '转化车辆', field: 'XZCBYNKSL'},
        { headerName: '转化率', field: 'XZCBYZHL'},
        { headerName: '车辆到店', field: 'YYFBYC'},
        { headerName: '转化车辆', field: 'YYCBYNKSL'},
        { headerName: '转化率', field: 'YYCBYZHL'},
        { headerName: '续卡车辆', field: 'XBYNKSL'},
        { headerName: '续卡占比', field: 'XBYZHL'},
        { headerName: '合计', field: 'HZ'}
      ]
    }]
  }

  getNkData(){
    return [{
      nkData: [
        { headerName: '年卡统计', field: 'TJRQ'},
        { headerName: '订单数', field: 'ZNKSL'},
        { headerName: '金额', field: 'ZNKJE'},
        { headerName: '均价', field: 'JJJE'},
        { headerName: '美容年卡', field: 'MRNKSL'},
        { headerName: '保养年卡', field: 'BYNKSL'}
      ]
    }]
}


  reportList = [
    {
      api: 'ipmMdzkForAppService.getGRBX',
      title: '今日保险',
      rowData: [],
      titleList: [
        {headerName: "人员", field: 'YWY', width: 120},
        {headerName: "报价数", field: 'BJS', width: 100},
        {headerName: "订单数", field: 'XDS', width: 100}
      ]
    },
    {
      api: 'ipmMdzkForAppService.getMDXS',
      title: '今日保养年卡',
      rowData: [],
      titleList: [
        {headerName: "接车人", field: 'JIECR', width: 120},
        {headerName: "接车数", field: 'JCS', width: 100},
        {headerName: "订单数", field: 'DDS', width: 100}
      ]
    }
  ]

  // 获取保养年卡转化
  getVip() {
    let data = { 'interfaceMethod': 'ipmXsrbService.getNKFXBB', 'pdata': { 'STARTDATE': this.times ,'MDID': this.posts } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            for(let i= 0, len = data.length; i < len ; i++){
              data[i]['YYCBYZHL'] = data[i]['YYCBYZHL'].toFixed(2) + '%';
              data[i]['XZCBYZHL'] = data[i]['XZCBYZHL'].toFixed(2) + '%';
              data[i]['XBYZHL'] = data[i]['XBYZHL'].toFixed(2) + '%';
              if(data[i].TJRQ === '日'){
                this.vipListRI = data[i];
              }
              if(data[i].TJRQ === '月'){
                this.vipListYUE = data[i];
              }
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取保险转化
  getBx() {
    let data = { 'interfaceMethod': 'ipmMdzkForAppService.getBXZH', 'pdata': { 'MDID': this.posts } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            let list = data.array;
            // console.log(list)
            for(let i= 0, len = list.length; i < len ; i++){
              if(list[i].BXZH === '日'){
                this.bxListRI = list[i];
              }
              if(list[i].BXZH === '月'){
                this.bxListYUE = list[i];
              }
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取年卡转化
  getNk() {
    let data = { 'interfaceMethod': 'ipmMdzkForAppService.getMDNKTJ', 'pdata': { 'MDID': this.posts } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            for(let i= 0, len = data.length; i < len ; i++){
              data[i].ZNKJE = data[i].ZNKJE.toFixed(2);
              data[i].JJJE = data[i].JJJE.toFixed(2);
              if(data[i].TJRQ === '日'){
                this.nkListRI = data[i];
              }
              if(data[i].TJRQ === '月'){
                this.nkListYUE = data[i];
              }
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取头部
  getHead() {
    let data = { 'interfaceMethod': 'ipmMgzzForAppService.getMGHead', 'pdata': { 'MDID': this.posts } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            data['XCJCL'] = data['XCJCL'] + '%';
            data['YTJ']['XCJCL'] = data['YTJ']['XCJCL'] + '%';
            this.headList = data;
            if( data.YTJ ){
              this.headYUEList = data.YTJ;
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  getTablesData(api:string, i:any ) {
    let data = { 'interfaceMethod': api, 'pdata': { 'MDID': this.posts } };
    this.apiService.post('report.interface', {'body': JSON.stringify(data)}).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            if(data.array === undefined){
              this.reportList[i].rowData = data;
            }else{
              this.reportList[i].rowData = data.array;
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

}
